import React, {forwardRef, useEffect, useImperativeHandle, useState,} from "react";
import {Form, Input, Modal, Select} from "antd";
import {addMenu, getIconDict} from "../../../api/modules/menu";



const ModalCom = (props: any, ref: any) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const  [icons,setIcons] = useState([]);
  const [form] = Form.useForm();
  const { getList } = props;
  useImperativeHandle(ref, () => {
    return {
      showModal: showModal,
    };
  });
  type FieldType = {
    username?: string;
    password?: string;
  };
  const showModal = (record: any,flag:boolean = false) => {
    if (record && !flag) {
      form.setFieldsValue(record);
    } else {
      form.resetFields();
      record && form.setFieldValue('pid',record.id)
      console.log(form.getFieldsValue(),'ssssssssssss')
    }
    setIsModalOpen(true);
  };

  const handleOk = () => {
    form
      .validateFields()
      .then(async (valid) => {
        const id = form.getFieldValue("id");
        const pid = form.getFieldValue("pid");
        const params = { ...valid, id,pid };
        const result = await addMenu(params);
        setIsModalOpen(false);
        getList();
      })
      .catch((err) => {
        return false;
      });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const getIcons = async ()=>{
   const  {data} =  await getIconDict();
    setIcons(data as any)
  }
  useEffect(()=>{
    getIcons()
  },[])

  const IconOption = icons.map((icon:any)=>{
    return {
      value:icon.value,
      label:icon.name
    }
  })
  return (
    <>
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="菜单名称"
            name="name"
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="菜单路径" name="path">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="图标" name="icon">
            <Select options={IconOption}>
              </Select>
          </Form.Item>
          <Form.Item<FieldType> label="描述" name="description">
              <Input />
          </Form.Item>

        </Form>
      </Modal>
    </>
  );
};

export default forwardRef(ModalCom);
